import collections


class Tree(object):
    def __init__(self, var):
        self.var = var
        self.neighbors = {}


class Trie(object):

    def __init__(self):
        self.tree = Tree('0')

    def insert(self, word):
        """
        :type word: str
        :rtype: None
        """
        tree = self.tree
        i = 0
        while i < len(word):
            if word[i] not in tree.neighbors:
                for j in range(i, len(word)):
                    new_tree = Tree(word[j])
                    tree.neighbors[word[j]] = new_tree
                    tree = new_tree
                i = len(word)
            else:
                tree = tree.neighbors[word[i]]
                i += 1
        tree.neighbors['0'] = Tree('0')

    def search(self, word):
        """
        :type word: str
        :rtype: bool
        """
        tree = self.tree
        for i in range(len(word)):
            if word[i] not in tree.neighbors:
                return False
            else:
                tree = tree.neighbors[word[i]]
        if '0' in tree.neighbors:
            return True
        else:
            return False

    def startsWith(self, prefix):
        """
        :type prefix: str
        :rtype: bool
        """
        tree = self.tree
        for i in range(len(prefix)):
            if prefix[i] not in tree.neighbors:
                return False
            else:
                tree = tree.neighbors[prefix[i]]
        return True

obj = Trie()
obj.insert('apple')
print(obj.search('apple'))
print(obj.search('app'))